import { getUserInfo, setUserInfo } from "../../utils/storage"
import { getCodeSession, GetCodeSessionDto } from '../../api/wxapi/index'
import { addUserCoin } from '../../api/wxuser/index'
import config from '../../config/index'
import { getCoinService } from '../../api/coinService/index'
import md5 from 'js-md5'
import { addRechargeRecord } from "../../api/rechargeRecord/index"
const dayjs = require("dayjs");

Component({
  properties: {
    panelShow: {
      type: Boolean,
      value: false
    },
  },
  data: {
    _index: 0,
    user: {} as WxUser,
    //当前选择的服务
    currentService: {} as ListCoinService,
    //服务列表
    coinServiceList: [] as ListCoinService[],
    //同意会员协议
    agree: false
  },
  lifetimes: {
    attached() {
      this.initData()
    }
  },
  methods: {
    compare(coinA: ListCoinService, coinB: ListCoinService): number{
      return coinA.coin - coinB.coin
    },
    async initData() {
      const user = getUserInfo()
      const res = await getCoinService()
      if(res.statusCode === config.SUCCESS_CODE) {
        let list = res.data as ListCoinService[]
        list.sort(this.compare)
        this.setData({
          coinServiceList: list,
          currentService: list[0],
          user
        })
      }
    },
    onClose() {
      this.setData({
        panelShow: false
      })
      this.triggerEvent('show', this.properties.panelShow)
    },
    chooseService(e: any) {
      this.setData({
        currentService: e.currentTarget.dataset.item,
        _index: e.currentTarget.dataset.index
      })
    },
    onChange(event: any) {
      this.setData({
        agree: event.detail,
      });
    },
    onSubmit() {
      let that = this
      wx.login({
        success (res: any) {
          let data: GetCodeSessionDto = {
            appid: config.appid,
            secret: config.secret,
            js_code: res.code,
            grant_type: 'authorization_code'
          }
          getCodeSession(data).then((res: any) => {
            that.pay(res.data.openid)
          })
        }
      })
    },
    pay(openid: string) {
      let mchntCd = '0003050F5420999'
      let randomStr = Array(25).fill('').map(() => Math.random().toString(36).charAt(2)).join('');
      let length = 10; // 生成的字符串长度
      let randomNum = Math.random().toString().substr(2, length); // 生成全是数字的随机字符串
      let nowTime = dayjs().format('YYYYMMDDHHmmss')
      wx.request({
        url: 'https://aipay.fuioupay.com/aggregatePay/wxPreCreate',
        method: 'POST',
        data: {
          'version': '1.0',
          'mchnt_cd': mchntCd,
          'random_str': randomStr, 
          'order_type': 'WECHAT',
          'transaction_id': '',
          'user_id': '',
          'order_amt': String(this.data.currentService.price * 100),
          'settle_order_amt': String(this.data.currentService.price * 100),
          'curr_type': '',
          'mchnt_order_no': '11411' + randomNum,
          'product_id': '',
          'goods_des': '充值积分',
          'goods_detail': '',
          'txn_begin_ts': nowTime,
          'term_id': '2u32ir34',
          'goods_tag': '',
          'term_ip': '139.224.135.193',
          'addn_inf': '',
          'notify_url': 'https://aipaytest.fuioupay.com/aggregatePay/preCreate',
          'limit_pay': '',
          'trade_type': 'LETPAY',
          'openid': openid,
          'sub_openid': openid,
          'sub_appid': config.appid,
          'reserved_fy_term_id': '',
          'reserved_expire_minute': '',
          'reserved_user_creid': '',
          'reserved_user_truename': '',
          'reserved_user_mobile': '',
          'reserved_bxno_inf': '',
          'reserved_fy_term_type': '',
          'reserved_fy_term_sn': '',
          'reserved_device_info': '',
          'reserved_ali_extend_params': '',
          'sign': md5(`${mchntCd}|LETPAY|${String(this.data.currentService.price * 100)}|11411${randomNum}|${nowTime}|充值积分|2u32ir34|139.224.135.193|https://aipaytest.fuioupay.com/aggregatePay/preCreate|${randomStr}|1.0|cad07470c16511ed7c076197eeda9e44`),
          'reserved_terminal_info': ''
        },
        success: (res: any) => {
          console.log(res.data);
          console.log(res.data.reserved_channel_order_id);
          if(res.data.result_code === '000000') {
            let timeStamp = res.data.sdk_timestamp
            let nonceStr = res.data.sdk_noncestr
            let packageStr = res.data.sdk_package
            let singTypeStr = res.data.sdk_signtype
            let paySignStr = res.data.sdk_paysign
            let merchantId = res.data.reserved_channel_order_id
            wx.requestPayment({
              timeStamp,
              nonceStr,
              package: packageStr,
              signType: singTypeStr,
              paySign: paySignStr,
              success: async () => {
                //支付成功后创建订单记录
              let recordData = {
                  merchantId,
                  phone: this.data.user.phone,
                  details: `充值${this.data.currentService.coin}积分`,
                  price: this.data.currentService.price,
                  orderTime: dayjs.unix(timeStamp).format('YYYY-MM-DD HH:mm:ss')
                } as RechargeRecord
                //创建订单记录
                const recordRes = await addRechargeRecord(recordData)
                if(recordRes.statusCode === config.CREATED_CODE) {
                  this.addCount()
                }
              },
              fail: () => {
                wx.showToast({title: '支付失败', icon: 'none'})
              },
              complete: () => {
              }
            })
          }
        }
      })
    },
    //添加次数
    async addCount() {
      const user = this.data.user
      const currentService = this.data.currentService
      let data = {
        coin: currentService.coin
      }
      const res = await addUserCoin(user.id, data)
      if(res.statusCode === config.CREATED_CODE) {
        setUserInfo(res.data)
        const user = getUserInfo()
        this.setData({
          user
        })
        wx.showToast({title: '开通成功', icon: 'success'})
        this.onClose()
        setTimeout(() => {
          this.triggerEvent('reLaunch')
        }, 1000)
      } else {
        wx.showToast({title: '开通失败', icon: 'error'})
      }
    },
    //跳转隐私政策
    toPolicy() {
      wx.downloadFile({
        url: config.BaseUrl + '/files/policy.pdf',
        success: (res) => {
          wx.openDocument({
            filePath: res.tempFilePath
          })
        } 
      })
    },
    //跳转会员服务协议
    toProtocol() {
      wx.downloadFile({
        url: config.BaseUrl + '/files/protocol.pdf',
        success: (res) => {
          wx.openDocument({
            filePath: res.tempFilePath
          })
        } 
      })
    }
  }
})
